//
//  HOTDumpListViewController.m
//  Genpara
//
//  Created by AndyChang.zhang on 14-9-11.
//  Copyright (c) 2014年 zhangchh. All rights reserved.
//

#import "HOTDumpListViewController.h"
#import "HOTDumpListCell.h"
#import "HOTEntryViewController.h"
#import "HOTNavigationViewController.h"

@interface HOTDumpListViewController () <UITableViewDataSource, UITableViewDelegate, HOTEntryViewControllerDelegate>{
    
    //NSArray *_dataList;
    //__unsafe_unretained HOTDumpListViewController *tempObj;
    NSInteger _pageNo;
    HOTNavigationViewController *nav_;
}

@property(nonatomic,strong)NSMutableArray *dataList;
@end

@implementation HOTDumpListViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setNaviTitle:@"現場掲示板"];
    
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg_dump"]];
    
    _tableView.backgroundColor = [UIColor clearColor];
#if 0
    
    _dataList = @[@{@"num":@"0001",@"name":@"ゆーじ",@"dateTime":@"2014-09-01-14:25",@"content":@"ゆーじ"},
                  @{@"num":@"0002",@"name":@"ゆーじ",@"dateTime":@"2014-09-01-14:25",@"content":@"ゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじ"},
                  @{@"num":@"0003",@"name":@"ゆーじ",@"dateTime":@"2014-09-01-14:25",@"content":@"ゆーじ"},
                  @{@"num":@"0004",@"name":@"ゆーじ",@"dateTime":@"2014-09-01-14:25",@"content":@"ゆーじ"},
                  @{@"num":@"0005",@"name":@"ゆーじ",@"dateTime":@"2014-09-01-14:25",@"content":@"ゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじda"},
                  @{@"num":@"0006",@"name":@"ゆーじ",@"dateTime":@"2014-09-01-14:25",@"content":@"ゆーじ"},
                  @{@"num":@"0007",@"name":@"ゆーじ",@"dateTime":@"2014-09-01-14:25",@"content":@"ゆーじ"},
                  @{@"num":@"0008",@"name":@"ゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじゆーじ",@"dateTime":@"2014-09-01-14:25",@"content":@"ゆーじ"},
                  @{@"num":@"0009",@"name":@"ゆーじ",@"dateTime":@"2014-09-01-14:25",@"content":@"ゆーじ"},
                  @{@"num":@"0010",@"name":@"ゆーじ",@"dateTime":@"2014-09-01-14:25",@"content":@"ゆーじ"},
                  @{@"num":@"0011",@"name":@"ゆーじ",@"dateTime":@"2014-09-01-14:25",@"content":@"ゆーじ"},
                  @{@"num":@"0012",@"name":@"ゆーじ",@"dateTime":@"2014-09-01-14:25",@"content":@"ゆーじ"},
                  @{@"num":@"0013",@"name":@"ゆーじ",@"dateTime":@"2014-09-01-14:25",@"content":@"ゆーじ"}];
    
#endif
    
    __unsafe_unretained HOTDumpListViewController *tempObj = self;
    
    [self showChatInputBar:YES];
    
    self.chatInputBar.sendBtnClicked = ^(NSString *sendMsg) {
        
        if ([tempObj userAuthorized]) {
            [tempObj replayClosure:sendMsg];
        }
        
    };
    
    _tableView.frame = CGRectMake(_tableView.frame.origin.x, _tableView.frame.origin.y, _tableView.frame.size.width, _tableView.frame.size.height - self.chatInputBar.frame.size.height);
    
    
    _tableView.showHeader = YES;
    _tableView.showFooter = YES;
    
    _tableView.headerView.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        
        _pageNo = 1;
        [tempObj requestDataFromNet];
    };

    _tableView.footerView.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        
        _pageNo ++;
        [tempObj requestDataFromNet];
    };
    
    UITapGestureRecognizer  *tgr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapTable)];
    [tgr setNumberOfTapsRequired:1];
    [tgr setNumberOfTouchesRequired:1];
    
    [_tableView addGestureRecognizer:tgr];
    
    self.dataList = [NSMutableArray array];
    
    _pageNo = 1;
    [self requestDataFromNet];
}

-(void)tapTable {
    
    [self.chatInputBar.chatTextView resignFirstResponder];
}

-(void)replayClosure:(NSString *)sendMsg {
    __unsafe_unretained HOTDumpListViewController *tempObj = self;
    NSDictionary *parameters = @{REQ_KEY_USER_TOKEN:self.userInfo.token,
                                 REQ_KEY_USER_ID:self.userInfo.userId,
                                 REQ_KEY_WORKP_ID:[HOTUtils getString:self.workId],
                                 REQ_KEY_REPLAY_CONTENT:[HOTUtils getString:sendMsg]};
    
    [self showLoading];
    [self requestWithURL:HOT_URL_MOCK_REPLAY Parameters:parameters success:^(NSInteger result, NSArray * dataArr) {
        
        [tempObj loadingSuccess];
        
        NSLog(@"评论成功");
        
        NSDate *curDate = [NSDate date];
        NSString *curDateStr = [ZZZUtils formartDate:curDate withStyle:@"yyyy-MM-dd hh:mm:ss"];
        int newId = 1;
        if (tempObj.dataList.count > 0) {
            newId = [[[tempObj.dataList lastObject] objectForKey:@"mock_id"] intValue];
        }
        NSDictionary *newCommon = @{@"mock_id":[NSString stringWithFormat:@"%d",++newId],
                                    @"user_nick":[HOTUtils getString:tempObj.userInfo.nick],
                                    @"mock_time":curDateStr,
                                    @"mock_content":[HOTUtils getString:sendMsg]
                                    };
        [tempObj.chatInputBar.chatTextView resignFirstResponder];
        [tempObj.dataList addObject:newCommon];
        NSIndexPath *insertIndex = [NSIndexPath indexPathForRow:tempObj.dataList.count-1 inSection:0];
        
        [tempObj->_tableView insertRowsAtIndexPaths:@[insertIndex] withRowAnimation:UITableViewRowAnimationBottom];
        
        [tempObj->_tableView scrollToRowAtIndexPath:insertIndex atScrollPosition:UITableViewScrollPositionTop animated:YES];
        
    } failure:^(NSError *error, NSString *errMsg) {
        
        [tempObj loadingSuccess];
        
        if ([tempObj checkErrResult:error errMsg:errMsg]) {
            return ;
        }
        if (errMsg.length > 0) {
            
            ZZZPopupView *popupView = [[ZZZPopupView alloc] initWithTitle:ALERT_TITLE
                                                                  message:errMsg
                                                                 delegate:nil
                                                        cancelButtonTitle:nil
                                                         otherButtonTitle:ALERT_BTN_OK];
            //[popupView setOffset:CGPointMake(0, -90)];
            [popupView showInWindow];
        }
    }];
}

-(void)requestDataFromNet {
    
    [self showLoading];
    __unsafe_unretained HOTDumpListViewController *tempObj = self;
    NSDictionary *parameters = @{REQ_KEY_USER_TOKEN:self.userInfo.token,
                                 REQ_KEY_USER_ID:self.userInfo.userId,
                                 REQ_KEY_WORKP_ID:[HOTUtils getString:self.workId],
                                 REQ_KEY_P_NUM:@(_pageNo),
                                 REQ_KEY_P_SIZE:kPageCnt};

    [self requestWithURL:HOT_URL_MOCK_LIST Parameters:parameters success:^(NSInteger result, NSArray * dataArr) {
        
        [tempObj loadingSuccess];
        [_tableView.headerView endRefreshing];
        [_tableView.footerView endRefreshing];
        if (dataArr.count == 0) {
            
            if (_pageNo == 1) {
                
                [tempObj.dataList removeAllObjects];
                [_tableView reloadData];
                [self alertNoDataMessage:^{
                    //[tempObj.navigationController popViewControllerAnimated:YES];
                }];
            } else {
                [self alertNoDataAgainMessage:nil];
            }
            
            
            return;
        }
        
        if (_pageNo == 1) {
            [tempObj.dataList removeAllObjects];
        }
        [tempObj.dataList addObjectsFromArray:dataArr];
        
        [_tableView reloadData];
        
    } failure:^(NSError *error, NSString *errMsg) {
        
        [tempObj loadingSuccess];
        [_tableView.headerView endRefreshing];
        [_tableView.footerView endRefreshing];
        if ([tempObj checkErrResult:error errMsg:errMsg]) {
            return ;
        }
        if (errMsg.length > 0) {
            
            ZZZPopupView *popupView = [[ZZZPopupView alloc] initWithTitle:ALERT_TITLE
                                                                  message:errMsg
                                                                 delegate:nil
                                                        cancelButtonTitle:nil
                                                         otherButtonTitle:ALERT_BTN_OK];
            
            [popupView showInWindow];
        }
    }];
}

-(void)chatBarFrameWillChange:(CGPoint)newPoint {
    
    _tableView.frame = CGRectMake(_tableView.frame.origin.x, _tableView.frame.origin.y, _tableView.frame.size.width, newPoint.y);
    
    if (self.dataList.count > 0) {
        [_tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.dataList.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }
}


#pragma mark - UItableView DataSource
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *cellId = @"cellID";
    HOTDumpListCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    
    if (cell == nil) {
        
        UINib *nib = [UINib nibWithNibName:XIB(@"HOTDumpListCell") bundle:nil];
        [tableView registerNib:nib forCellReuseIdentifier:cellId];
        
        cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSDictionary *dic = [_dataList objectAtIndex:indexPath.row];
    [cell setData:[dic objectForKey:@"mock_id"]
             name:[dic objectForKey:@"user_nick"]
         dateTime:[dic objectForKey:@"mock_time"]
          content:[dic objectForKey:@"mock_content"]];
    cell.nameLabel.user_id = [dic objectForKey:@"user_id"];
    return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.dataList.count;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSDictionary *dic = [_dataList objectAtIndex:indexPath.row];
    
    static NSString *cellId = @"cellID";
    HOTDumpListCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    
    if (cell == nil) {
        
        UINib *nib = [UINib nibWithNibName:XIB(@"HOTDumpListCell") bundle:nil];
        [tableView registerNib:nib forCellReuseIdentifier:cellId];
        
        cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    [cell setData:[dic objectForKey:@"mock_id"]
             name:[dic objectForKey:@"user_nick"]
         dateTime:[dic objectForKey:@"mock_time"]
          content:[dic objectForKey:@"mock_content"]];
    

    [cell setNeedsDisplay];
    [cell setNeedsUpdateConstraints];
    [cell.contentView setNeedsDisplay];
    [cell.contentView setNeedsUpdateConstraints];
    
    float cellH = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
    //float height = [self getCellHeightWithContent:[dic objectForKey:@"content"]];
    return cellH+1;
}

-(float)getCellHeightWithContent:(NSString *)content {
    
    NSDictionary *stringAttr = @{NSFontAttributeName:ZZZ_fontWithName(kHOT_FONT_HIRAGINO_KAKU_W3, 12)};
    CGRect rect = [content boundingRectWithSize:CGSizeMake(292, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:stringAttr context:nil];
    
    float labHeight = rect.size.height;
    labHeight = labHeight < 25 ? 25 : labHeight;
    
    return labHeight +
    34+ //contentLabel y坐标
    8  //下引号的高度
    +2 // 下引号与bgView的padding高度
    +1; //分割线的高度
}

- (BOOL)userAuthorized
{
    HOTUserInfo *userInfo = [HOTUserInfo defaultUser];
    
    if ([userInfo isLogined]) {
        return YES;
    } else {
        HOTEntryViewController *entryVC = [[HOTEntryViewController alloc] initWithNibName:@"HOTEntryViewController" bundle:nil];
        entryVC.delegate = self;
        [entryVC setNaviTitle:@"入場"];
        nav_ = [HOTNavigationViewController createNaviWithRootViewController:entryVC];
        [self presentViewController:nav_ animated:YES completion:nil];
        return NO;
    }
    return YES;
}

#pragma mark - HOTEntryViewControllerDelegate

- (void)entrySuccessed
{
    [nav_ dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - UITableView Delegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
